package listo.client;

import com.google.inject.Singleton;
import org.apache.commons.lang.StringUtils;

import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.ResourceBundle;

@Singleton
public class Lang {

    private ResourceBundle uiBundle = ResourceBundle.getBundle("lang.UI");

    private Locale locale;
    private DateFormat dateFormat;
    private DateFormat shortDateFormat;
    private DateFormat timeFormat;

    public void configure(String lang) {
        String s[] = StringUtils.split(lang.trim(), '-');
        locale = "system".equals(lang) ? Locale.getDefault() : new Locale(s[0], s[1]);
        uiBundle = ResourceBundle.getBundle("lang.UI", locale);
    }

    public String get(String key) {
        try {
            String value = uiBundle.getString(key);
            return StringUtils.isEmpty(value) ? value : new String(value.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException();
        }
    }

    public String get(String format, Object... args) {
        return uiBundle.getString(String.format(format, args));
    }

    public DateFormat getDateFormat() {
        if (dateFormat == null) {
            String pattern = get("datePattern");
            dateFormat = "system".equals(pattern) ?
                    DateFormat.getDateInstance(DateFormat.SHORT, locale) :
                    new SimpleDateFormat(pattern);
        }
        return dateFormat;
    }

    public DateFormat getShortDateFormat() {
        if (shortDateFormat == null) {
            String pattern = get("shortDatePattern");
            shortDateFormat = "system".equals(pattern) ?
                    DateFormat.getDateInstance(DateFormat.SHORT, locale) :
                    new SimpleDateFormat(pattern);
        }
        return shortDateFormat;
    }

    public DateFormat getTimeFormat() {
        if (timeFormat == null) {
            String pattern = get("timePattern");
            timeFormat = "system".equals(pattern) ?
                    DateFormat.getTimeInstance(DateFormat.SHORT, locale) :
                    new SimpleDateFormat(pattern);
        }
        return timeFormat;
    }

}
